package com.yin.waimai.service.impl;

import com.yin.waimai.dto.AddressDTO;
import com.yin.waimai.service.AddressCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class AddressCacheServiceImpl implements AddressCacheService {

    private static final String ADDRESS_KEY_PREFIX = "user:address:";
    private static final long CACHE_EXPIRATION = 30; // 缓存过期时间（天）

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void saveUserAddress(String userId, AddressDTO address) {
        // 为地址生成一个唯一ID（如果没有的话）
        if (address.getId() == null || address.getId().isEmpty()) {
            address.setId(UUID.randomUUID().toString());
        }
        
        String key = getAddressKey(userId);
        redisTemplate.opsForHash().put(key, address.getId(), address);
        redisTemplate.expire(key, CACHE_EXPIRATION, TimeUnit.DAYS);
    }

    @Override
    public List<AddressDTO> getUserAddresses(String userId) {
        String key = getAddressKey(userId);
        List<Object> values = redisTemplate.opsForHash().values(key);
        
        if (values == null || values.isEmpty()) {
            return new ArrayList<>();
        }
        
        return values.stream()
                .filter(obj -> obj instanceof AddressDTO)
                .map(obj -> (AddressDTO) obj)
                .collect(Collectors.toList());
    }

    @Override
    public boolean deleteUserAddress(String userId, String addressId) {
        String key = getAddressKey(userId);
        return redisTemplate.opsForHash().delete(key, addressId) > 0;
    }

    @Override
    public void clearUserAddresses(String userId) {
        String key = getAddressKey(userId);
        redisTemplate.delete(key);
    }

    private String getAddressKey(String userId) {
        return ADDRESS_KEY_PREFIX + userId;
    }
}